/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2010 UCL
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: João Taveira Araújo  <j.araujo@ucl.ac.uk> 
 */
 
#include "reflex-trace.h"
 
NS_LOG_COMPONENT_DEFINE ("ReflexTraceQueue");

TypeId
ReflexTraceQueue::GetTypeId ()
{
  static TypeId tid = TypeId("ns3::ReflexTraceQueue")
    .SetParent<Object> ()
    ;
  return tid;
}
  
ReflexTraceQueue::ReflexTraceQueue()
{}

ReflexTraceQueue::~ReflexTraceQueue() 
{
  ascii.close();
}

void ReflexTraceQueue::SetDevice(std::string prefix, Ptr<NetDevice> device)
{
  NS_ASSERT(device);
  AsciiTraceHelper p;
  ascii.open(p.GetFilenameFromDevice (prefix, device, false).c_str());
}


void ReflexTraceQueue::LogQueue(std::string prefix, Ptr<NetDevice> device)
{
}

void PppReflexTraceQueue::LogQueue(std::string prefix, Ptr<NetDevice> device)
{
  SetDevice(prefix,device);
  Ptr<PointToPointNetDevice> ptp = DynamicCast<PointToPointNetDevice> (device); 

  Ptr<Queue> queue = ptp->GetQueue();
  queue->TraceConnectWithoutContext("Dequeue", MakeCallback(&ReflexTraceQueue::TxDequeue, this));
  queue->TraceConnectWithoutContext("Drop", MakeCallback(&ReflexTraceQueue::TxDrop, this));
}



uint32_t
ReflexTraceQueue::GetReflex(Ptr< Packet> p) 
{
  if( p )
  {
    Ipv4Header ipv4Header;
    p->PeekHeader(ipv4Header);
    uint32_t reflex = ipv4Header.GetFlags() & Ipv4Header::RESERVED_BIT;
    reflex += ipv4Header.GetTos(Ipv4Header::ECN_MASK);
    return reflex;
  }
  return 0;
}


/* Still no perfect, should callback to caller with reflex codepoint + packet.
*/
void 
ReflexTraceQueue::TxDrop(Ptr<const Packet> p)
{
  ascii << "d ";
  Log(p);
}    
                
void 
ReflexTraceQueue::TxDequeue(Ptr<const Packet> p)
{
  ascii << "s ";
  Log(p);
}                

void 
ReflexTraceQueue::TxEnqueue(Ptr<const Packet> p)
{
  ascii << "e ";
  Log(p);
}             
             
void 
ReflexTraceQueue::Log(Ptr<const Packet> p)
{
  Ptr<Packet> pkt = ProcessHeader(p);
  ascii << Simulator::Now().GetTimeStep() << " " << GetReflex(pkt) << " " <<  pkt->GetSize() << '\n';
}            

Ptr<Packet> 
PppReflexTraceQueue::ProcessHeader(Ptr<const Packet> p)
{
  Ptr<Packet> tmp = p->Copy();
  PppHeader pppHeader;
  tmp->RemoveHeader(pppHeader);
  if ( pppHeader.GetProtocol() == IP_PROTO_NUM )
    return tmp;
  return 0;
}

